package com.rede.didiok.admin.service.impl;

import java.util.*;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import cn.hutool.core.lang.Assert;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rede.didiok.admin.dao.AdminDao;
import com.rede.didiok.admin.entity.AdminEntity;
import com.rede.didiok.admin.entity.RoleEntity;
import com.rede.didiok.admin.service.AdminService;
import com.rede.didiok.admin.service.RoleService;
import com.rede.didiok.admin.service.SysParamsService;
import com.rede.didiok.admin.utils.FileUtil;
import com.rede.didiok.common.constant.conf.MessageConf;
import com.rede.didiok.common.constant.conf.RedisConf;
import com.rede.didiok.common.constant.conf.SQLConf;
import com.rede.didiok.common.constant.conf.SysConf;
import com.rede.didiok.common.constant.global.Constants;
import com.rede.didiok.common.dto.admin.AdminDto;
import com.rede.didiok.common.dto.admin.OnlineAdminDto;
import com.rede.didiok.common.dto.user.UserDto;
import com.rede.didiok.common.enums.StatusEnum;
import com.rede.didiok.common.exception.exceptionType.FeignException;
import com.rede.didiok.common.exception.exceptionType.QueryException;
import com.rede.didiok.common.feign.FileFeignClient;
import com.rede.didiok.common.feign.UserFeignClient;
import com.rede.didiok.common.holder.RequestHolder;
import com.rede.didiok.common.utils.*;
import com.rede.didiok.common.utils.business.UserUtil;
import com.rede.didiok.common.utils.business.WebUtil;


@Service("adminService")
public class AdminServiceImpl extends ServiceImpl<AdminDao, AdminEntity> implements AdminService {

    @Autowired
    UserFeignClient userFeignClient;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    WebUtil webUtil;
    @Autowired
    UserUtil userUtil;
    @Autowired
    SysParamsService sysParamsService;
    @Autowired
    private FileUtil fileUtil;
    @Resource
    private FileFeignClient fileFeignClient;
    @Autowired
    private RoleService roleService;
    @Autowired
    private AdminDao adminDao;

    /***************************** didiok-admin:start ************************/
    // region didiok-admin

    /**
     * 获取管理员列表
     *
     * @param adminDto
     * @return
     */
    @Override
    public IPage<AdminEntity> getList(AdminDto adminDto) {
        // 根据 keyword 查询管理员列表
        QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
        String pictureResult = null;
        if (StringUtils.isNotEmpty(adminDto.getKeyword())) {
            queryWrapper.like(SQLConf.USER_NAME, adminDto.getKeyword()).or().like(SQLConf.NICKNAME, adminDto.getKeyword().trim());
        }
        Page<AdminEntity> page = new Page<>();
        page.setCurrent(adminDto.getCurrentPage());
        page.setSize(adminDto.getPageSize());
        // 去除密码
        queryWrapper.select(AdminEntity.class, i -> !i.getProperty().equals(SQLConf.PASSWORD));
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        IPage<AdminEntity> pageList = this.page(page, queryWrapper);
        List<AdminEntity> list = pageList.getRecords();

        final StringBuilder fileUids = new StringBuilder();
        List<String> adminUidList = new ArrayList<>();
        // 权限附身的用户
        List<String> userUidList = new ArrayList<>();
        list.forEach(item -> {
            if (StringUtils.isNotEmpty(item.getAvatar())) {
                fileUids.append(item.getAvatar() + SysConf.FILE_SEGMENTATION);
            }
            if (StringUtils.isNotEmpty(item.getUserUid())) {
                userUidList.add(item.getUserUid());
            }
            adminUidList.add(item.getUid());

        });

        Map<String, String> pictureMap = new HashMap<>(com.rede.didiok.common.constant.global.Constants.NUM_TEN);
        if (fileUids != null) {
            pictureResult = fileFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION);
        }
        List<Map<String, Object>> picList = fileUtil.getPictureMap(pictureResult);
        picList.forEach(item -> {
            pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString());
        });
        Map<String, UserDto> userMap = new HashMap<>();
        if (userUidList.size() > 0) {
            // 根据用户uid列表查询用户
            R result = userFeignClient.listUserByUids(userUidList);
            List<UserDto> userDtoList;
            if(result.getCode()==0){
                userDtoList = result.getData(new TypeReference<List<UserDto>>(){});
            }else {
                // 获取异常信息
                String msg = result.getData("msg",new TypeReference<String>(){});
                throw new FeignException("feign调用异常（根据用户uid列表查询用户）："+msg);
            }

            if (userDtoList.size() > 0) {
                List<UserDto> userList = userUtil.convertUserList(userDtoList);
                for (UserDto user : userList) {
                    userMap.put(user.getUid(), user);
                }
            }
        }

        for (AdminEntity item : list) {
            RoleEntity role = roleService.getById(item.getRoleUid());
            item.setRole(role);

            //获取图片
            if (StringUtils.isNotEmpty(item.getAvatar())) {
                List<String> pictureUidsTemp = StringUtils.changeStringToString(item.getAvatar(), SysConf.FILE_SEGMENTATION);
                List<String> pictureListTemp = new ArrayList<>();
                pictureUidsTemp.forEach(picture -> {
                    if (pictureMap.get(picture) != null && pictureMap.get(picture) != "") {
                        pictureListTemp.add(pictureMap.get(picture));
                    }
                });
                item.setPhotoList(pictureListTemp);
            }

            // 设置权限附身的用户
            if (StringUtils.isNotEmpty(item.getUserUid()) && userMap.get(item.getUserUid()) != null) {
                item.setUser(userMap.get(item.getUserUid()));
            }

        }
        return pageList;
    }

    /**
     * 重置密码
     *
     * @param adminDto
     * @return
     */
    @Override
    public String resetPwd(AdminDto adminDto) {
        String defaultPassword = sysParamsService.getSysParamsValueByKey(SysConf.SYS_DEFAULT_PASSWORD);
        // 获取当前用户的管理员uid
        String adminUid = RequestHolder.getAdminUid();
        AdminEntity admin = this.getById(adminDto.getUid());
        // 判断是否是admin重置密码【其它超级管理员，无法重置admin的密码】
        if (SysConf.ADMIN.equals(admin.getUserName()) && !admin.getUid().equals(adminUid)) {
            return ResultUtil.errorWithMessage(MessageConf.UPDATE_ADMIN_PASSWORD_FAILED);
        } else {
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            admin.setPassword(encoder.encode(defaultPassword));
            admin.updateById();
            return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
        }
    }

    /**
     * 添加管理员
     *
     * @param adminDto
     * @return
     */
    @Override
    public String addAdmin(AdminDto adminDto) {

        String mobile = adminDto.getMobile();
        String userName = adminDto.getUserName();
        String email = adminDto.getEmail();
        if (StringUtils.isEmpty(userName)) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        if (StringUtils.isEmpty(email) && StringUtils.isEmpty(mobile)) {
            return ResultUtil.errorWithMessage("邮箱和手机号至少一项不能为空");
        }
        String defaultPassword = sysParamsService.getSysParamsValueByKey(SysConf.SYS_DEFAULT_PASSWORD);
        QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.USER_NAME, userName);
        AdminEntity temp = this.getOne(queryWrapper);
        if (temp == null) {
            AdminEntity admin = new AdminEntity();
            admin.setAvatar(adminDto.getAvatar());
            admin.setEmail(adminDto.getEmail());
            admin.setGender(adminDto.getGender());
            admin.setUserName(adminDto.getUserName());
            admin.setNickname(adminDto.getNickname());
            admin.setRoleUid(adminDto.getRoleUid());
            // 绑定用户
            admin.setUserUid(adminDto.getUserUid());
            // 设置为审核状态
            admin.setStatus(StatusEnum.ENABLE);
            PasswordEncoder encoder = new BCryptPasswordEncoder();
            //设置默认密码
            admin.setPassword(encoder.encode(defaultPassword));
            this.save(admin);
            //TODO 这里需要通过SMS模块，发送邮件告诉初始密码

            return ResultUtil.successWithMessage(MessageConf.INSERT_SUCCESS);
        }
        return ResultUtil.errorWithMessage(MessageConf.ENTITY_EXIST);
    }

    /**
     * 编辑管理员
     *
     * @param adminDto
     * @return
     */
    @Override
    public String editAdmin(AdminDto adminDto) {
        AdminEntity admin = this.getById(adminDto.getUid());
        Assert.notNull(admin, MessageConf.PARAM_INCORRECT);
        //判断修改的对象是否是admin，admin的用户名必须是admin
        if (admin.getUserName().equals(SysConf.ADMIN) && !adminDto.getUserName().equals(SysConf.ADMIN)) {
            return ResultUtil.errorWithMessage("超级管理员用户名必须为admin");
        }
        QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.eq(SQLConf.USER_NAME, adminDto.getUserName());
        List<AdminEntity> adminList = this.list(queryWrapper);
        if (adminList != null) {
            for (AdminEntity item : adminList) {
                if (item.getUid().equals(adminDto.getUid())) {
                    continue;
                } else {
                    return ResultUtil.errorWithMessage("修改失败，用户名存在");
                }
            }
        }

        // 判断是否更改了RoleUid，更新redis中admin的URL访问路径
        if (StringUtils.isNotEmpty(adminDto.getRoleUid()) && !adminDto.getRoleUid().equals(admin.getRoleUid())) {
            redisUtil.delete(RedisConf.ADMIN_VISIT_MENU + RedisConf.SEGMENTATION + admin.getUid());
        }
        admin.setUserName(adminDto.getUserName());
        admin.setAvatar(adminDto.getAvatar());
        admin.setNickname(adminDto.getNickname());
        admin.setGender(adminDto.getGender());
        admin.setEmail(adminDto.getEmail());
        admin.setQqNumber(adminDto.getQqNumber());
        admin.setGithub(adminDto.getGithub());
        admin.setGitee(adminDto.getGitee());
        admin.setOccupation(adminDto.getOccupation());
        admin.setMobile(adminDto.getMobile());
        admin.setRoleUid(adminDto.getRoleUid());
        // 绑定用户
        admin.setUserUid(adminDto.getUserUid());
        // 无法直接修改密码，只能通过重置密码完成密码修改
        admin.setPassword(null);
        admin.updateById();

        // 更新完成
        return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
    }

    /**
     * 批量删除管理员
     *
     * @param adminUidList
     * @return
     */
    @Override
    public String deleteBatchAdmin(List<String> adminUidList) {
        boolean checkResult = StringUtils.checkUidList(adminUidList);
        if (!checkResult) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        List<AdminEntity> adminList = new ArrayList<>();
        adminUidList.forEach(item -> {
            AdminEntity admin = new AdminEntity();
            admin.setUid(item);
            admin.setStatus(StatusEnum.DISABLED);
            adminList.add(admin);
        });
        this.updateBatchById(adminList);
        return ResultUtil.successWithMessage(MessageConf.DELETE_SUCCESS);
    }

    /**
     * 获取在线用户列表
     *
     * @param adminDto
     * @return
     */
    @Override
    public String getOnlineAdminList(AdminDto adminDto) {
        // 获取Redis中匹配的所有key
        Set<String> keys = redisUtil.keys(RedisConf.ONLINE_ADMIN_LIST + "*");
        List<String> onlineAdminJsonList = redisUtil.multiGet(keys);
        // 拼装分页信息
        int pageSize = adminDto.getPageSize().intValue();
        int currentPage = adminDto.getCurrentPage().intValue();
        int total = onlineAdminJsonList.size();
        int startIndex = Math.max((currentPage - 1) * pageSize, 0);
        int endIndex = Math.min(currentPage * pageSize, total);
        //TODO 截取出当前分页下的内容，后面考虑用Redis List做分页
        List<String> onlineAdminSubList = onlineAdminJsonList.subList(startIndex, endIndex);
        List<OnlineAdminDto> onlineAdminList = new ArrayList<>();
        for (String item : onlineAdminSubList) {
            OnlineAdminDto onlineAdmin = JsonUtils.jsonToPojo(item, OnlineAdminDto.class);
            // 数据脱敏【移除用户的token令牌】
            onlineAdmin.setToken("");
            onlineAdminList.add(onlineAdmin);
        }
        Page<OnlineAdminDto> page = new Page<>();
        page.setCurrent(currentPage);
        page.setTotal(total);
        page.setSize(pageSize);
        page.setRecords(onlineAdminList);
        return ResultUtil.successWithData(page);
    }

    /**
     * 强退用户
     * @param tokenUidList
     * @return
     */
    @Override
    public String forceLogout(List<String> tokenUidList) {
        if (tokenUidList == null || tokenUidList.size() == 0) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }

        // 从Redis中通过TokenUid获取到用户的真实token
        List<String> tokenList = new ArrayList<>();
        tokenUidList.forEach(item -> {
            String token = redisUtil.get(RedisConf.LOGIN_UUID_KEY + RedisConf.SEGMENTATION + item);
            if (StringUtils.isNotEmpty(token)) {
                tokenList.add(token);
            }
        });

        // 根据token删除Redis中的在线用户
        List<String> keyList = new ArrayList<>();
        List<String> onlineList = new ArrayList<>();
        String onlinePrefix = RedisConf.ONLINE_ADMIN_LIST + RedisConf.SEGMENTATION;
        String keyPrefix = String.format("%s:%s:", RedisConf.LOGIN_TOKEN_KEY, "ADMIN");
        for (String token : tokenList) {
            keyList.add(keyPrefix + token);
            onlineList.add(onlinePrefix + token);
        }
        redisUtil.delete(keyList);
        redisUtil.delete(onlineList);

        return ResultUtil.successWithMessage(MessageConf.OPERATION_SUCCESS);
    }

    /**
     * 添加在线用户
     *
     * @param admin            管理员
     * @param expirationSecond 过期时间【秒】
     */
    @Override
    public void addOnlineAdmin(AdminEntity admin, Long expirationSecond) {
        HttpServletRequest request = RequestHolder.getRequest();
        Map<String, String> map = IpUtils.getOsAndBrowserInfo(request);
        String os = map.get(SysConf.OS);
        String browser = map.get(SysConf.BROWSER);
        String ip = IpUtils.getIpAddr(request);
        OnlineAdminDto onlineAdmin = new OnlineAdminDto();
        onlineAdmin.setAdminUid(admin.getUid());
        onlineAdmin.setTokenId(admin.getTokenUid());
        onlineAdmin.setToken(admin.getValidCode());
        onlineAdmin.setOs(os);
        onlineAdmin.setBrowser(browser);
        onlineAdmin.setIpaddr(ip);
        onlineAdmin.setLoginTime(DateUtils.getNowTime());

        onlineAdmin.setUserName(admin.getUserName());
        onlineAdmin.setExpireTime(DateUtils.getDateStr(new Date(), expirationSecond));

        RoleEntity role = roleService.getById(admin.getRoleUid());
        if (role != null) {
            onlineAdmin.setRoleName(role.getRoleName());
        }

        //从Redis中获取IP来源
        String jsonResult = redisUtil.get(RedisConf.IP_SOURCE + Constants.SYMBOL_COLON + ip);
        if (StringUtils.isEmpty(jsonResult)) {
            String addresses = IpUtils.getAddresses(ip, SysConf.UTF_8);
            if (StringUtils.isNotEmpty(addresses)) {
                onlineAdmin.setLoginLocation(addresses);
                redisUtil.setEx(RedisConf.IP_SOURCE + Constants.SYMBOL_COLON + ip, addresses, 24, TimeUnit.HOURS);
            }
        } else {
            onlineAdmin.setLoginLocation(jsonResult);
        }
        // 将登录的管理员存储到在线用户表
        redisUtil.setEx(RedisConf.ONLINE_ADMIN_LIST + RedisConf.SEGMENTATION + admin.getValidCode(), JsonUtils.objectToJson(onlineAdmin), expirationSecond, TimeUnit.SECONDS);
        // 在维护一张表，用于 uuid - token 互相转换
        redisUtil.setEx(RedisConf.LOGIN_UUID_KEY + RedisConf.SEGMENTATION + admin.getTokenUid(), admin.getValidCode(), expirationSecond, TimeUnit.SECONDS);

    }

    @Override
    public AdminEntity getMe() {
        HttpServletRequest request = RequestHolder.getRequest();
        if (request.getAttribute(SysConf.ADMIN_UID) == null || request.getAttribute(SysConf.ADMIN_UID) == "") {
            return new AdminEntity();
        }
        AdminEntity admin = this.getById(request.getAttribute(SysConf.ADMIN_UID).toString());
        //清空密码，防止泄露
        admin.setPassword(null);
        //获取图片
        if (StringUtils.isNotEmpty(admin.getAvatar())) {
            String pictureList = fileFeignClient.getPicture(admin.getAvatar(), com.rede.didiok.common.constant.global.Constants.SYMBOL_COMMA);
            admin.setPhotoList(fileUtil.getPicture(pictureList));
        }
        return admin;
    }

    @Override
    public String editMe(AdminDto adminDto) {
        String adminUid = RequestHolder.getAdminUid();
        if (StringUtils.isEmpty(adminUid)) {
            return ResultUtil.errorWithMessage(MessageConf.INVALID_TOKEN);
        }
        AdminEntity admin = new AdminEntity();
        // 【使用Spring工具类提供的深拷贝，减少大量模板代码】
        BeanUtils.copyProperties(adminDto, admin, SysConf.STATUS);
        admin.setUpdateTime(new Date());
        admin.updateById();
        return ResultUtil.successWithMessage(MessageConf.OPERATION_SUCCESS);
    }

    @Override
    public String changePwd(String oldPwd, String newPwd) {
        String adminUid = RequestHolder.getAdminUid();
        if (StringUtils.isEmpty(oldPwd) || StringUtils.isEmpty(newPwd)) {
            return ResultUtil.errorWithMessage(MessageConf.PARAM_INCORRECT);
        }
        AdminEntity admin = this.getById(adminUid);
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean isPassword = encoder.matches(oldPwd, admin.getPassword());
        if (isPassword) {
            admin.setPassword(encoder.encode(newPwd));
            admin.setUpdateTime(new Date());
            admin.updateById();
            return ResultUtil.successWithMessage(MessageConf.UPDATE_SUCCESS);
        } else {
            return ResultUtil.errorWithMessage(MessageConf.ERROR_PASSWORD);
        }
    }

    // endregion
    /***************************** didiok-admin:end **************************/

    /**************************** didiok-web:start ***************************/
    // region didiok-web

    @Override
    public AdminEntity getAdminByUser(String userName) {
        QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.USER_NAME, userName);
        queryWrapper.last(SysConf.LIMIT_ONE);
        //清空密码，防止泄露
        AdminEntity admin = this.getOne(queryWrapper);
        admin.setPassword(null);
        //获取图片
        if (StringUtils.isNotEmpty(admin.getAvatar())) {
            String pictureList = fileFeignClient.getPicture(admin.getAvatar(), com.rede.didiok.common.constant.global.Constants.SYMBOL_COMMA);
            admin.setPhotoList(fileUtil.getPicture(pictureList));
        }
        AdminEntity result = new AdminEntity();
        result.setNickname(admin.getNickname());
        result.setOccupation(admin.getOccupation());
        result.setSummary(admin.getSummary());
        result.setAvatar(admin.getAvatar());
        result.setPhotoList(admin.getPhotoList());
        if (StringUtils.isNotEmpty(admin.getPersonResume())) {
            result.setPersonResume(admin.getPersonResume().replaceAll(" src=", " data-src="));
        }
        return result;
    }

    /**
     * 根据 userUid 查询绑定的管理员账号数量
     *
     * @param userUid
     */
    @Override
    public Integer countAdminByUserUid(String userUid) {
        QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, StatusEnum.ENABLE);
        queryWrapper.eq(SQLConf.USER_UID, userUid);
        return this.count(queryWrapper);
    }

    /**
     * 通过 id 更新管理员密码
     *
     * @param adminUid
     * @param password
     * @return
     */
    @Override
    public Boolean updateAdminPasswordById(String adminUid, String password) {
        return adminDao.updateAdminPasswordById(adminUid, password);
    }

    @Override
    public List<AdminEntity> getAdminListByUids(Collection<String> uidList) {

        if (uidList.size() == 0) {
            throw new QueryException(MessageConf.PARAM_INCORRECT);
        }
        QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(SQLConf.UID, uidList);
        List<AdminEntity> adminList = this.list(queryWrapper);

        final StringBuilder fileUids = new StringBuilder();
        for (AdminEntity admin : adminList) {
            if (StringUtils.isNotEmpty(admin.getAvatar())) {
                fileUids.append(admin.getAvatar() + SysConf.FILE_SEGMENTATION);
            }
        }
        //获取图片
        Map<String, String> pictureMap = new HashMap<>(Constants.NUM_TEN);
        String pictureResult = null;
        if (fileUids != null) {
            pictureResult = fileFeignClient.getPicture(fileUids.toString(), SysConf.FILE_SEGMENTATION);
        }
        List<Map<String, Object>> picList = fileUtil.getPictureMap(pictureResult);
        picList.forEach(item -> {
            pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString());
        });
        List<AdminEntity> result = new ArrayList<>();
        for (AdminEntity tempAdmin : adminList) {
            AdminEntity admin = new AdminEntity();
            // 数据脱敏
            admin.setUid(tempAdmin.getUid());
            admin.setPhotoUrl(tempAdmin.getPhotoUrl());
            admin.setSummary(tempAdmin.getSummary());
            admin.setNickname(tempAdmin.getNickname());
            admin.setGender(tempAdmin.getGender());
            admin.setOccupation(tempAdmin.getOccupation());
            String avatar = tempAdmin.getAvatar();
            if (StringUtils.isNotEmpty(avatar)) {
                if (pictureMap.get(avatar) != null && pictureMap.get(avatar) != "") {
                    admin.setPhotoUrl(pictureMap.get(avatar));
                }
            }
            result.add(admin);
        }
        return result;
    }

    // endregion
    /***************************** didiok-web:end ****************************/

    /**
     * 获取指定状态的管理员
     *
     * @param status
     * @return
     */
    @Override
    public List<AdminEntity> listAdminByStatus(Integer status) {
        QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(SQLConf.STATUS, status);
        return this.list(queryWrapper);
    }

    /**
     * 通过UIDs获取Admin
     *
     * @param uid@return
     */
    @Override
    public AdminEntity getAdminByUid(String uid) {

        if (StringUtils.isEmpty(uid)) {
            throw new QueryException(MessageConf.PARAM_INCORRECT);
        }
        AdminEntity admin = this.getById(uid);

        String fileUid = admin.getAvatar();
        //获取图片
        Map<String, String> pictureMap = new HashMap<>(Constants.NUM_TEN);
        String pictureResult = null;
        if (StringUtils.isNotEmpty(fileUid)) {
            pictureResult = fileFeignClient.getPicture(fileUid, SysConf.FILE_SEGMENTATION);
        }
        List<Map<String, Object>> picList = fileUtil.getPictureMap(pictureResult);
        picList.forEach(item -> {
            pictureMap.put(item.get(SQLConf.UID).toString(), item.get(SQLConf.URL).toString());
        });
        List<AdminEntity> result = new ArrayList<>();
        // 数据脱敏
        String avatar = admin.getAvatar();
        if (StringUtils.isNotEmpty(avatar)) {
            if (pictureMap.get(avatar) != null && pictureMap.get(avatar) != "") {
                admin.setPhotoUrl(pictureMap.get(avatar));
            }
        }
        return admin;
    }

    @Override
    public List<AdminEntity> getUserListWithoutAvatarByIds(Collection<String> uidList) {

        if (uidList.size() == 0) {
            throw new QueryException(MessageConf.PARAM_INCORRECT);
        }
        QueryWrapper<AdminEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.in(SQLConf.UID, uidList);
        List<AdminEntity> adminList = this.list(queryWrapper);

        final StringBuilder fileUids = new StringBuilder();
        for (AdminEntity admin : adminList) {
            if (StringUtils.isNotEmpty(admin.getAvatar())) {
                fileUids.append(admin.getAvatar() + SysConf.FILE_SEGMENTATION);
            }
        }

        List<AdminEntity> result = new ArrayList<>();
        for (AdminEntity tempAdmin : adminList) {
            AdminEntity admin = new AdminEntity();
            // 数据脱敏
            admin.setUid(tempAdmin.getUid());
            admin.setPhotoUrl(tempAdmin.getPhotoUrl());
            admin.setSummary(tempAdmin.getSummary());
            admin.setNickname(tempAdmin.getNickname());
            admin.setGender(tempAdmin.getGender());
            admin.setOccupation(tempAdmin.getOccupation());

            result.add(admin);
        }
        return result;
    }


    /**
     * 通过 id 获取管理员昵称
     *
     * @return
     */
    @Override
    public String getNicknameById(String uid) {
        return adminDao.getNicknameById(uid);
    }

}